const express = require('express');
const router = express.Router();
const db = require('../../../util/dbConfig/dbConfig')
const nowDate = require('../../../public/javascripts/nowDate')


router.post('/',async (req,res) => {
    let userInfo = req.session.userInfo
    let {
        year,                          //年度
    } = req.body
    if(!year){
        //默认当前年份
        year = nowDate().year
    }
    //02-12-2021  时间格式
    let aDate = year + '-' + nowDate().month + '-' + nowDate().day
    let aDate1 = Date.parse(aDate)
    try{
        let ramYear = 0   //周岁公羊
        let eweYear = 0  //周岁母羊
        let ramAdult = 0  //成年公羊
        let eweAdult = 0  //成年母羊
        let sql = `select BIRTHDAY from sheep where SEX=1 and YEAR(BIRTHDAY)<=${year}`
        let sql1 = `select BIRTHDAY from sheep where SEX=2 and YEAR(BIRTHDAY)<=${year}`
        if(userInfo.admin ===0){
            sql = sql + ' ' + `and USER_ID=${userInfo._id}`
            sql1 = sql1 + ' ' + `and USER_ID=${userInfo._id}`
        }

        //公羊是否成年

        let result = await db.SySqlConnect(sql,[])
        for(let i = 0; i<result.length; i++){
            let bYear = result[i]['BIRTHDAY'].getFullYear()
            let bMonth = result[i]['BIRTHDAY'].getMonth() + 1
            let bDay = result[i]['BIRTHDAY'].getDate()
            bMonth = bMonth>=10?bMonth:'0'+bMonth
            bDay = bDay>=10?bDay:'0'+bDay
            let bDate = bYear + '-' + bMonth + '-' + bDay
            let bDate1 = Date.parse(bDate)
            let iDays  =  parseInt(`${Math.abs(aDate1 - bDate1)/  1000  /  60  /  60  /24}`)    //把相差的毫秒数转换为天数
            iDays>365?ramAdult++:ramYear++
        }
        //母羊羊是否成年
        let result1 = await db.SySqlConnect(sql1,[])
        for(let i = 0; i<result1.length; i++){
            let bYear = result1[i]['BIRTHDAY'].getFullYear()
            let bMonth = result1[i]['BIRTHDAY'].getMonth() + 1
            let bDay = result1[i]['BIRTHDAY'].getDate()
            bMonth = bMonth>=10?bMonth:'0'+bMonth
            bDay = bDay>=10?bDay:'0'+bDay
            let bDate = bYear + '-' + bMonth + '-' + bDay
            let bDate1 = Date.parse(bDate)
            let iDays  =  parseInt(`${Math.abs(aDate1 - bDate1)/  1000  /  60  /  60  /24}`)    //把相差的毫秒数转换为天数
            iDays>365?eweAdult++:eweYear++
        }
        return res.send({
            code: 0,
            msg: `加载${year}年的数据成功`,
            year,   //当前年度
            data: {
                ramYear,        //周岁公羊
                eweYear,        //周岁母羊
                ramAdult,       //成年公羊
                eweAdult        //成年母羊
            }
        })
    }catch (e) {
        console.log(e);
        return res.send({
            code: 4,
            msg: '服务器错误，请稍后再试'
        })
    }

})

module.exports = router
